package com.yanx.system.base.domain.entity;

import com.yanx.codegen.annotation.CodeGenClass;
import com.yanx.codegen.annotation.CodeGenField;
import com.yanx.common.core.domain.entity.BaseTimeEntity;
import com.yanx.system.base.domain.entity.rel.SysRoleDept;
import com.yanx.system.base.domain.entity.rel.SysRoleMenu;
import com.yanx.system.base.domain.entity.rel.SysUserRole;
import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 角色表 sys_role
 *
 * @author gotanks
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "SYS_ROLE")
@CodeGenClass(value = "菜单权限", author = "gotanks")
public class SysRole extends BaseTimeEntity {
    private static final long serialVersionUID = 1L;

//    @CodeGenField("角色ID")
//    private Long roleId;

    @CodeGenField("角色名称")
    private String roleName;

    @CodeGenField("角色ID")
    private String roleKey;

    @CodeGenField("角色ID")
    private Integer roleSort;

    /**
     * 数据范围（1：所有数据权限；2：自定义数据权限；3：本部门数据权限；4：本部门及以下数据权限；5：仅本人数据权限）
     */
    @CodeGenField("数据范围")
    private String dataScope;

    /**
     * 菜单树选择项是否关联显示（ 0：父子不互相关联显示 1：父子互相关联显示）
     */
    @CodeGenField("菜单树选择项是否关联显示")
    private boolean menuCheckStrictly;

    /**
     * 部门树选择项是否关联显示（0：父子不互相关联显示 1：父子互相关联显示 ）
     */
    @CodeGenField("部门树选择项是否关联显示")
    private boolean deptCheckStrictly;

    /**
     * 角色状态（0正常 1停用）
     */
    @CodeGenField("角色状态")
    private String status;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "roleId", updatable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
    private List<SysRoleMenu> roleMenus = new ArrayList<>();

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "roleId", updatable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
    private List<SysRoleDept> roleDepts = new ArrayList<>();

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "roleId", updatable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
    private List<SysUserRole> userRoles = new ArrayList<>();

    public void addUserRole(Long userId, Long roleId) {
        if (userRoles.stream().noneMatch(s -> s.getUserId().equals(userId) && s.getRoleId().equals(roleId))) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(userId);
            userRoles.add(sysUserRole);
        }
    }
}
